package com.hjs.juc;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 *
 * @author hanjinsong
 * @date 2020-02-19 14:59
 */
public class TestProductorAndConsumer {

    public static void main(String[] args) {
        Clerk clerk = new Clerk();
        Productor productor = new Productor(clerk);
        Consumer consumer = new Consumer(clerk);

        new Thread(productor,"生产者A").start();
        new Thread(consumer,"消费者A").start();
    }
}

class Clerk {
    private int product = 0;
    Condition condition = new ReentrantLock().newCondition();


    //进货
    public synchronized void get() {
        while (product > 10) {
            System.out.println("产品已满");
            try {
                //this.wait();
                condition.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        System.out.println(Thread.currentThread().getName() +"进货："+ ++product);
        //this.notifyAll();
        condition.signalAll();
    }

    //卖货
    public synchronized void sale() {
        while (product <= 0) {
            System.out.println("没口罩");
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
            System.out.println(Thread.currentThread().getName()+"还剩"+ --product);
        this.notifyAll();
    }
}

class Productor implements Runnable {
    private Clerk clerk;
    public Productor (Clerk clerk){
        this.clerk = clerk;
    }

    @Override
    public void run() {
        for (int i = 0; i < 20; i++) {
            clerk.get();
        }
    }
}

class Consumer implements Runnable {
    private Clerk clerk;
    public Consumer (Clerk clerk){
        this.clerk = clerk;
    }

    @Override
    public void run() {
        for (int i = 0; i < 20; i++) {
            clerk.sale();
        }
    }
}
